﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using JQData.Core.TushareSDK.Models;
using System.Threading.Tasks;

namespace JQData.Core.TushareSDK
{
    //是用示例

    //var core = new TushareCore("你的token");
    //var stockApi = new StockApi(core);
    //var result = await stockApi.GetStockListAsync();




    /// <summary>
    /// Tushare API 基础封装
    /// </summary>
    public class TushareCore : IDisposable
    {
        private readonly string _baseUrl = "https://api.tushare.pro";
        private readonly string _token;
        private readonly HttpClient _httpClient;

        public TushareCore(string token)
        {
            _token = token ?? throw new ArgumentNullException(nameof(token));
            _httpClient = new HttpClient();
        }

        /// <summary>
        /// 通用 POST 请求
        /// </summary>
        /// <typeparam name="TResult">返回类型</typeparam>
        /// <param name="apiName">API 名称</param>
        /// <param name="parameters">API 参数</param>
        /// <param name="fields">可选的返回字段，以逗号分隔</param>
        /// <returns>API 返回的实际数据列表</returns>
        public async Task<TushareResponse<TResult>> CallApiAsync<TResult>(string apiName, object parameters, string fields = null)
        {
            var requestBody = new TushareRequest
            {
                ApiName = apiName,
                Token = _token,
                Params = parameters,
                Fields = fields
            };

            var jsonOptions = new JsonSerializerOptions
            {
                DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
                PropertyNameCaseInsensitive = true // Tushare API返回的字段可能是小写下划线，而我们的C#属性是PascalCase
            };
            var requestJson = JsonSerializer.Serialize(requestBody, jsonOptions);
            var content = new StringContent(requestJson, Encoding.UTF8, "application/json");

            var httpResponse = await _httpClient.PostAsync(_baseUrl, content);
            // 不立即调用 EnsureSuccessStatusCode()，以便能读取到Tushare返回的错误信息JSON
            // response.EnsureSuccessStatusCode(); 

            var responseJson = await httpResponse.Content.ReadAsStringAsync();

            // 首先尝试反序列化为标准的TushareResponse结构
            var tushareResponse = JsonSerializer.Deserialize<TushareResponse<TResult>>(responseJson, jsonOptions);

            if (tushareResponse == null)
            {
                // 如果 httpResponse 不是成功状态码，EnsureSuccessStatusCode 会抛出异常
                httpResponse.EnsureSuccessStatusCode();
                // 如果到了这里，说明 EnsureSuccessStatusCode 没抛异常，但反序列化失败了，这不应该发生
                throw new JsonException("Failed to deserialize Tushare response and no HTTP error occurred.");
            }

            if (tushareResponse.Code != 0)
            {
                throw new HttpRequestException($"Tushare API Error (Code: {tushareResponse.Code}): {tushareResponse.Msg}", null, httpResponse.StatusCode);
            }

            // 如果API调用成功，但没有返回数据项 (例如某些只返回状态的接口，或者确实没有数据)
            if (tushareResponse.Data == null || tushareResponse.Data.Items == null)
            {
                throw new Exception("Tushare API returned no data items. This might be due to an empty response or an error in the request parameters.");
            }

            return tushareResponse;
        }

        public void Dispose()
        {
            _httpClient?.Dispose();
        }
    }
}
